﻿/*
    My Console
*/

var console = {
    log: function (info) {
        var oldHtml = $('#divConsole').html();
        $('#divConsole').html(oldHtml + '<br />' + info);
    }
};

var ObjUtil = {
    // inherit() returns a newly created object that inherits properties 
    // from the prototype object p
    inherit: function(p) {
        if (p == null) throw TypeError(); // p must be a non-null object
        if (Object.create)                // If Object.create() is defined...
            return Object.create(p);      //    then just use it.
        var t = typeof p;                 // Otherwise do some more type checking
        if (t !== "object" && t !== "function") throw TypeError();
        function f() { };                  // Define a dummy constructor function.
        f.prototype = p;                  // Set its prototype property to p.

        return new f();                   // Use f() to create an "heir" of p.
    },

    /* get class attribute of object */
    getClass: function(o) {
        if (o === null) return "Null";
        if (o === undefined) return "Undefined";

        return Object.prototype.toString.call(o).slice(8,-1);
    },

    deepCopy: function (obj) {
        var jsonObj = JSON.stringify(obj);
        var cloneObj = JSON.parse(jsonObj);

        return cloneObj;
    },

    // Print the name and value of each property of object
    printProperties: function (obj) {
        for (var p in obj) {
            if ((typeof obj[p]).toString() == "object") {
                arguments.callee(obj[p]);
            } else {
                console.log(p + ": " + obj[p] + "\n");
            }
        }
    },

    //judge is function
    isFunction: function (p) {
        return Object.prototype.toString.call(p) === "[object Function]";
    }
};




var ArrayUtil = {
    /*
        find all matched index in array
        and push them into another array
     */

    findMatchIndexes: function(arr, elem) {
        var results = [],
            len = arr.length,
            pos = 0;

        while (pos < len) {
            pos = arr.indexOf(elem, pos);
            if (pos == -1) break;
            results.push(pos);
            pos++;
        }

        return results;
    }
};

var CacheUtil = {
    memorize: function (f) {
        var cache = {};

        return function () {
            var key = arguments.length + Array.prototype.join.call(arguments, ",");
            if (key in cache)
                return cache[key];
            else
                return cache[key] = f.apply(this, arguments);
        };
    }
};
